/**
 * 自定义协议『序列化、反序列化 byte[]』
 */
var msgpack = require('msgpack');

// 序列化 格式|length(4byte)|type(1byte)|msgpackbody(var length)|
exports.packWithType = function(object, type) {
	// 使用msgpack序列化
	var buffer = msgpack.pack(object);
	// 重新构建buffer—帧化buffer，格式|length(4byte)|type(1byte)|msgpackbody(var length)|
	var framedBuffer = new Buffer(buffer.length + 4 + 1);
	// 写包体长度到前4个字节
  	framedBuffer.writeInt32BE(buffer.length, 0);
  	// 写类型到帧化buffer的第5个字节
  	framedBuffer.writeUInt8(type, 4);
  	// 将包体复制到帧化buffer，从第6个字节开始
  	buffer.copy(framedBuffer, 5);
  	
  	return framedBuffer;
}

// 反序列化 格式|length(4byte)|type(1byte)|msgpackbody(var length)|
exports.unpackWithType = function(framedBuffer) {
	// console.log(framedBuffer); 
	var length = framedBuffer.readInt32BE(0); // 读出前4位byte[]转为int，表示字符长度
	// console.log(length); 1
	var type = framedBuffer.readUInt8(4); // 读出第5位byte，转为8bit integer类型.此时值固定为1，表示消息类型
	var unframedbuffer = framedBuffer.slice(5, 5 + length); // 从第6位到buffer最后一位的新buffer(byte数组)
	// console.log(unframedbuffer);
	var unpack = msgpack.unpack(unframedbuffer);
	// console.log(unpack);
	return {message: unpack, type: type};
}

// 根据之前协议得到一条完整的信息
exports.getWholeWrap = function(buffers) {
	console.log('received data length:' + buffers.length); 

	var length = buffers.readInt32BE(0); // 读出前4位byte[]转为int，表示字符长度
	console.log("WholeWrap content size: " + length);

	var type = buffers.readUInt8(4); // 读出第5位byte，转为8bit integer类型.此时值固定为1，表示消息类型
	var unframedbuffer = buffers.slice(5); // 从第6位到buffer最后一位的新buffer(byte数组)

	if(length == unframedbuffer.length) { // 此次buffer流刚刚好是一条完整信息
		// var framedBuffer =  buffers.slice(5); 
		var unpack = msgpack.unpack(unframedbuffer);
		// console.log(unpack);
		return {isWrap: true, message: unpack, type: type, buffer: null};
	} else if(length < unframedbuffer.length) { // 本次buffer流还附带下一条信息部分
		var framedBuffer =  buffers.slice(5, length); 
		var unpack = msgpack.unpack(framedBuffer);
		buffers = buffers.slice(length + 5); // 重新计算buffer（byte[]）
		return {isWrap: true, message: unpack, type: type, buffer: buffers};
	} else { // 不够一次完整信息，此次不解包
		return {isWrap: false, message: null, buffer: buffers};	
	}
}